import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'dart:ui';

import 'package:flutter/animation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_constraintlayout/flutter_constraintlayout.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:path_provider/path_provider.dart';
import 'package:wch/constant/config_constant.dart';
import 'package:wch/constant/resource_constant.dart';
import 'package:wch/helper/preferences_helper.dart';
import 'package:wch/page/stage_sub.dart';
import 'package:wch/utils/loading_utils.dart';
import 'package:wch/utils/log_utils.dart';
import 'package:wch/utils/navigator_utils.dart';
import 'package:wch/utils/time_utils.dart';
import 'package:wch/utils/toast_utils.dart';
import 'package:wch/widget/alert_view.dart';
import 'package:wch/widget/common_widget.dart';
import 'package:wch/widget/padding_widget.dart';
import 'package:wch/widget/text_widget.dart';
import 'package:wch_plugin/wch_plugin.dart';

import '../model/report_detail_entity.dart';
import '../native/net_business.dart';

class DataStagePage extends StatefulWidget {
  const DataStagePage({super.key, required this.id});
  final String id;

  @override
  State<DataStagePage> createState() => _DataStagePageState();
}

class _DataStagePageState extends State<DataStagePage> {
  OverlayEntry? entry;

  GlobalKey awakenImageKey = GlobalKey();
  GlobalKey awakenTextKey = GlobalKey();
  GlobalKey filterIconKey = GlobalKey();
  GlobalKey eeWidgetKey = GlobalKey();
  GlobalKey titleWidgetKey = GlobalKey();

  Offset? awakenImageOffset;
  Offset? filterIconOffset;
  Offset? eegWidgetOffset;
  Size? eegWidgetSize;

  int totalPage = 0;
  int currentPage = 1;

  double yAxis = 200;
  double maxYAxis = 14000;
  double minYAxis = 20;
  double awakenTextX = 0;
  double awakenTextY = 0;
  double awakenTextWidth = 0;
  double awakenTextHeight = 0;
  double originAwakenTextX = 0;
  double originAwakenTextY = 0;
  double titleWidgetHeight = 0;

  List<int> datas = [];

  List<int> stages = [];
  List<int> oldStages = [];

  double ratio = 1;

  int filterType = 2;

  double moveOffsetX = 0;
  double moveOffsetY = 0;
  int eventType = -1;///当前事件类型，-1无类型，0按下微觉醒按钮，1按下微觉醒事件

  ReportDetailEntity entity = ReportDetailEntity();
  ///edf 本地路径
  String localEdfPath = '';
  String edfName = '';
  String reportId = '';

  List<AwakenModel> awakenModels = [];
  ///按下的微觉醒事件
  AwakenModel? selectedAwakenModel;
  ///报告开始时间戳
  int startTimeStamp = 0;

  @override
  // Widget build(BuildContext context) {
  //   return KeyboardDismissOnTap(
  //     child: CommonScaffold(
  //       key: titleWidgetKey,
  //         title: '查看数据',
  //         body: Container(
  //           color: themeBGC,
  //           margin: EdgeInsets.only(left: statusBarHeight),
  //           child: Listener(
  //             onPointerDown: (p) {
  //               // LogUtils.log('p.localPosition.dy=${p.localPosition.dy+statusBarHeight+titleWidgetHeight}');
  //               LogUtils.log('p.localPosition.dy=${p.localPosition.dy+statusBarHeight+titleWidgetHeight}');
  //               // LogUtils.log('p.localPosition.dx=${p.localPosition.dx}');
  //               // LogUtils.log('awakenTextY=$awakenTextY');
  //               if (p.localPosition.dx + statusBarHeight > awakenTextX &&
  //                   p.localPosition.dx + statusBarHeight < awakenTextX + awakenTextWidth && p.localPosition.dy + statusBarHeight + titleWidgetHeight > awakenTextY &&
  //                   p.localPosition.dy + statusBarHeight + titleWidgetHeight < awakenTextY + 100) {
  //                   LogUtils.log('222');
  //                   setState(() {
  //                     eventType = 0;
  //                   });
  //                   moveOffsetX = p.localPosition.dx - awakenTextX;
  //                   moveOffsetY = p.localPosition.dy - awakenTextY;
  //               } else {//是否按压到了微觉醒事件
  //                 LogUtils.log('333');
  //                 for (int i = 0; i < awakenModels.length; i ++) {
  //                   AwakenModel model = awakenModels[i];
  //                   // LogUtils.log('model!.dx=${model.x}');
  //                   // LogUtils.log('model!.dy=${model.y}');
  //                   // LogUtils.log('eegWidgetSize!.height=${eegWidgetSize!.height}');
  //                   if (p.localPosition.dy + statusBarHeight > model.y && p.localPosition.dy + statusBarHeight < model.y + eegWidgetSize!.height) {
  //                     LogUtils.log('log');
  //                     if (p.localPosition.dx > model.x - 7.5.w && p.localPosition.dx < model.x + 1.5.w + 7.5.w) {
  //                       LogUtils.log('按下第$i个');
  //                       eventType = 1;
  //                       selectedAwakenModel = model;
  //                       moveOffsetX = p.localPosition.dx;
  //                       moveOffsetY = p.localPosition.dy;
  //                       break;
  //                     }
  //                   }
  //                 }
  //               }
  //             },
  //             onPointerMove: (p) {
  //               if (eventType == -1) return;
  //               // LogUtils.log('onPointerMove');
  //               if (eventType == 0) {
  //                 setState(() {
  //                   double textX = p.localPosition.dx;
  //                   double textY = p.localPosition.dy;
  //                   LogUtils.log('textX=$textX');
  //                   LogUtils.log('textY=$textY');
  //                   awakenTextX = textX;
  //                   awakenTextY = textY + 10;
  //                 });
  //               } else if (eventType == 1) {
  //                 selectedAwakenModel!.x = p.localPosition.dx;
  //                 selectedAwakenModel!.y = p.localPosition.dy;
  //                 LogUtils.log('selectedAwakenModel=${selectedAwakenModel!.x}');
  //                 LogUtils.log('selectedAwakenModel=${selectedAwakenModel!.y}');
  //                 setState(() {
  //                   awakenModels;
  //                 });
  //               }
  //             },
  //             onPointerUp: (p) {
  //               if (eventType == -1) return;
  //
  //               LogUtils.log('onPointerUp');
  //               setState(() {
  //                 // LogUtils.log('p.localPosition.dx=${p.localPosition.dx + statusBarHeight}');
  //                 // LogUtils.log('p.localPosition.dy=${p.localPosition.dy + statusBarHeight}');
  //                 // LogUtils.log('eegWaveOffset!.dx=${eegWidgetOffset!.dx}');
  //                 // LogUtils.log('eegWaveOffset!.dy=${eegWidgetOffset!.dy}');
  //                 // LogUtils.log('eegWaveSize!.width=${eegWidgetSize!.width}');
  //                 // LogUtils.log('eegWaveSize!.height=${eegWidgetSize!.height}');
  //                 if (eventType == 0) {
  //                   if (p.localPosition.dx + statusBarHeight> eegWidgetOffset!.dx && p.localPosition.dx +statusBarHeight < eegWidgetOffset!.dx + eegWidgetSize!.width) {
  //                     if (p.localPosition.dy + statusBarHeight > eegWidgetOffset!.dy && p.localPosition.dy + statusBarHeight < eegWidgetOffset!.dy + eegWidgetSize!.height) {
  //                       AwakenModel model = AwakenModel(p.localPosition.dx, eegWidgetOffset!.dy, true, false, p.localPosition.dx, eegWidgetOffset!.dy);
  //                       model.page = currentPage;
  //                       double timeStamp = startTimeStamp + (currentPage-1)*30*1000 + (p.localPosition.dx-40)/eegWidgetSize!.width*30*1000;
  //                       model.timeStamp = timeStamp.toInt();
  //                       awakenModels.add(model);
  //                     }
  //                   }
  //                   awakenTextX = originAwakenTextX;
  //                   awakenTextY = originAwakenTextY;
  //                 } else if (eventType == 1){
  //                   if (selectedAwakenModel!.x > 40 && selectedAwakenModel!.y < eegWidgetOffset!.dy + eegWidgetSize!.height - 5 && selectedAwakenModel!.y + eegWidgetSize!.height - 5 > eegWidgetOffset!.dy + 5) {
  //                     selectedAwakenModel!.y = selectedAwakenModel!.originY;
  //                     double timeStamp = startTimeStamp + (currentPage-1)*30*1000 + (p.localPosition.dx-40)/eegWidgetSize!.width*30*1000;
  //                     selectedAwakenModel!.timeStamp = timeStamp.toInt();
  //                     setState(() {
  //                       awakenModels;
  //                     });
  //                   } else {
  //                     awakenModels.remove(selectedAwakenModel);
  //                   }
  //                 }
  //               });
  //
  //               eventType = -1;
  //             },
  //             child: Container(
  //               child: Stack(
  //                 children: widgets(),
  //               ),
  //             ),
  //           ),
  //         )),
  //   );
  // }
  Widget build(BuildContext context) {
    return KeyboardDismissOnTap(
      child: Container(
          color: themeBGC,
          margin: EdgeInsets.only(left: statusBarHeight),
          child: Listener(
              onPointerDown: (p) {
                // LogUtils.log('p.localPosition.dy=${p.localPosition.dy+statusBarHeight+titleWidgetHeight}');
                LogUtils.log('p.localPosition.dy=${p.localPosition.dy+titleWidgetHeight}');
                // LogUtils.log('p.localPosition.dx=${p.localPosition.dx}');
                // LogUtils.log('awakenTextY=$awakenTextY');
                if (p.localPosition.dx > awakenTextX &&
                    p.localPosition.dx < awakenTextX + awakenTextWidth && p.localPosition.dy  + titleWidgetHeight > awakenTextY &&
                    p.localPosition.dy + titleWidgetHeight < awakenTextY + 100) {
                  LogUtils.log('222');
                  setState(() {
                    eventType = 0;
                  });
                  moveOffsetX = p.localPosition.dx - awakenTextX;
                  moveOffsetY = p.localPosition.dy - awakenTextY;
                } else {//是否按压到了微觉醒事件
                  LogUtils.log('333');
                  for (int i = 0; i < awakenModels.length; i ++) {
                    AwakenModel model = awakenModels[i];
                    // LogUtils.log('model!.dx=${model.x}');
                    // LogUtils.log('model!.dy=${model.y}');
                    // LogUtils.log('eegWidgetSize!.height=${eegWidgetSize!.height}');
                    if (p.localPosition.dy + statusBarHeight > model.y && p.localPosition.dy + statusBarHeight < model.y + eegWidgetSize!.height) {
                      LogUtils.log('log');
                      if (p.localPosition.dx > model.x - 7.5.w && p.localPosition.dx < model.x + 1.5.w + 7.5.w) {
                        LogUtils.log('按下第$i个');
                        eventType = 1;
                        selectedAwakenModel = model;
                        moveOffsetX = p.localPosition.dx;
                        moveOffsetY = p.localPosition.dy;
                        break;
                      }
                    }
                  }
                }
              },
              onPointerMove: (p) {
                if (eventType == -1) return;
                // LogUtils.log('onPointerMove');
                if (eventType == 0) {
                  setState(() {
                    double textX = p.localPosition.dx;
                    double textY = p.localPosition.dy;
                    LogUtils.log('textX=$textX');
                    LogUtils.log('textY=$textY');
                    awakenTextX = textX;
                    awakenTextY = textY + 10;
                  });
                } else if (eventType == 1) {
                  selectedAwakenModel!.x = p.localPosition.dx;
                  selectedAwakenModel!.y = p.localPosition.dy;
                  LogUtils.log('selectedAwakenModel=${selectedAwakenModel!.x}');
                  LogUtils.log('selectedAwakenModel=${selectedAwakenModel!.y}');
                  setState(() {
                    awakenModels;
                  });
                }
              },
              onPointerUp: (p) {
                if (eventType == -1) return;

                LogUtils.log('onPointerUp');
                setState(() {
                  // LogUtils.log('p.localPosition.dx=${p.localPosition.dx + statusBarHeight}');
                  // LogUtils.log('p.localPosition.dy=${p.localPosition.dy + statusBarHeight}');
                  // LogUtils.log('eegWaveOffset!.dx=${eegWidgetOffset!.dx}');
                  // LogUtils.log('eegWaveOffset!.dy=${eegWidgetOffset!.dy}');
                  // LogUtils.log('eegWaveSize!.width=${eegWidgetSize!.width}');
                  // LogUtils.log('eegWaveSize!.height=${eegWidgetSize!.height}');
                  if (eventType == 0) {
                    if (p.localPosition.dx + statusBarHeight> eegWidgetOffset!.dx && p.localPosition.dx +statusBarHeight < eegWidgetOffset!.dx + eegWidgetSize!.width) {
                      if (p.localPosition.dy + statusBarHeight > eegWidgetOffset!.dy && p.localPosition.dy + statusBarHeight < eegWidgetOffset!.dy + eegWidgetSize!.height) {
                        AwakenModel model = AwakenModel(p.localPosition.dx, eegWidgetOffset!.dy, true, false, p.localPosition.dx, eegWidgetOffset!.dy);
                        model.page = currentPage;
                        double timeStamp = startTimeStamp + (currentPage-1)*30*1000 + (p.localPosition.dx-40)/eegWidgetSize!.width*30*1000;
                        model.timeStamp = timeStamp.toInt();
                        awakenModels.add(model);
                      }
                    }
                    awakenTextX = originAwakenTextX;
                    awakenTextY = originAwakenTextY;
                  } else if (eventType == 1){
                    if (selectedAwakenModel!.x > 40 && selectedAwakenModel!.y < eegWidgetOffset!.dy + eegWidgetSize!.height - 5 && selectedAwakenModel!.y + eegWidgetSize!.height - 5 > eegWidgetOffset!.dy + 5) {
                      selectedAwakenModel!.y = selectedAwakenModel!.originY;
                      double timeStamp = startTimeStamp + (currentPage-1)*30*1000 + (p.localPosition.dx-40)/eegWidgetSize!.width*30*1000;
                      selectedAwakenModel!.timeStamp = timeStamp.toInt();
                      setState(() {
                        awakenModels;
                      });
                    } else {
                      awakenModels.remove(selectedAwakenModel);
                    }
                  }
                });

                eventType = -1;
              },
              child: Container(
                child: Stack(
                  children: widgets(),
                ),
              )
          )),
    );
  }

  List<Widget> widgets() {
    List<Widget> widgets = [
      ConstraintLayout(
        children: [
          Container(
            color: Colors.white,
            child: ConstraintLayout(
              children: [
                GestureDetector(
                  child: Icon(
                    Icons.arrow_back_ios,
                    color: Colors.black,
                  ),
                  onTap: (){
                    NavigatorUtil.pop(context);
                  },
                ).applyConstraint(
                    left: parent.left.margin(30),
                    width: 9,
                    height: 17,
                    clickPadding: EdgeInsets.all(20),
                    centerVerticalTo: parent
                ),
                Text('查看数据', style: TextStyle(
                  color: Color(0xFF3E3F42),
                  fontWeight: FontWeight.w600,
                  fontSize: 17
                ),).applyConstraint(
                  centerTo: parent
                )
              ],
            ),
          ).applyConstraint(
            left: parent.left,
            right: parent.right,
            top: parent.top,
            height: 55,
            width: matchConstraint,
          ),
          Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(7.5.w)), color: Colors.white),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                const HorPadding(18),
                Image.asset(
                  entity.data!.sex == '男' ? patientMaleImg : patientFemaleImg,
                  width: 30,
                  height: 30,
                ),
                const HorPadding(8),
                Row(
                  children: [
                    SizedBox(
                      width: 160,
                      child: Row(
                        children: [
                          Container(
                              constraints: const BoxConstraints(maxWidth: 120),
                              child: Text(
                                entity.data!.userName ?? '',
                                overflow: TextOverflow.ellipsis,
                                style: const TextStyle(color: F1TextColor, fontWeight: FontWeight.w500, fontSize: 15),
                              )
                          ),
                          const HorPadding(10),
                          Image.asset(
                            entity.data!.sex == '男' ? patientMaleIcon : patientFemaleIcon,
                            width: 18,
                            height: 18,
                          ),
                        ],
                      ),
                    ),
                    F13TitleText('${entity.data!.age ?? '0'}岁', color: F2TextColor),
                    const HorPadding(15),
                    LineWidget(width: 1, height: 15.h),
                    const HorPadding(15),
                    F13TitleText(entity.data!.mobile ?? '', color: F2TextColor),
                  ],
                )
              ],
            ),
          ).applyConstraint(
            right: parent.right.margin(5),
            height: 45,
            left: parent.left.margin(5),
            width: matchConstraint,
            top: rId(0).bottom.margin(5),
          ),
          Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(7.5.w)), color: themeBGC),
            child: ConstraintLayout(
              children: [
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w)), color: Colors.white,
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      const VerPadding(10),
                      const Row(
                        children: [
                          HorPadding(10),
                          F11TitleText('分期标定', color: F1TextColor),
                        ],
                      ),
                      const VerPadding(5),
                      Row(
                        mainAxisSize: MainAxisSize.max,
                        children: [
                          const HorPadding(10),
                          Expanded(
                            child: Container(
                                height: 26,
                                decoration: const BoxDecoration(color: Color(0xFFF3F5FA), borderRadius: BorderRadius.all(Radius.circular(15))),
                                child: ConstraintLayout(
                                  children: [
                                    GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            stages[currentPage - 1] = 4;
                                          });
                                        },
                                        child: Container(
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(
                                            borderRadius: const BorderRadius.all(Radius.circular(15)),
                                            color: stages.isEmpty ? Colors.transparent : (stages[currentPage - 1] == 4 || stages[currentPage - 1] == 5) ? themeColor : Colors.transparent,
                                          ),
                                          child: F11TitleText('WK', color: stages.isEmpty ? Colors.black : (stages[currentPage - 1] == 4 || stages[currentPage - 1] == 5) ? Colors.white : Colors.black),
                                        )
                                    ).applyConstraint(
                                      left: parent.left,
                                      widthPercent: 0.25,
                                      width: matchConstraint,
                                      widthPercentageAnchor: PercentageAnchor.parent,
                                      top: parent.top,
                                      bottom: parent.bottom,
                                    ),
                                    GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            stages[currentPage - 1] = 2;
                                          });
                                        },
                                        child: Container(
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(15)), color: stages.isEmpty ? Colors.transparent : stages[currentPage - 1] == 2 ? themeColor : Colors.transparent,),
                                          child: F11TitleText('LT', color: stages.isEmpty ? Colors.black :  stages[currentPage - 1] == 2 ? Colors.white : Colors.black),)
                                    ).applyConstraint(
                                      left: rId(0).right,
                                      widthPercent: 0.25,
                                      width: matchConstraint,
                                      widthPercentageAnchor: PercentageAnchor.parent,
                                      top: parent.top,
                                      bottom: parent.bottom,
                                    ),
                                    GestureDetector(
                                      onTap: () {
                                        setState(() {
                                          stages[currentPage - 1] = 1;
                                        });
                                      },
                                      child: Container(
                                        alignment: Alignment.center,
                                        decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(15)),
                                          color: stages.isEmpty ? Colors.transparent :  stages[currentPage - 1] == 1 ? themeColor : Colors.transparent,),
                                        child: F11TitleText('DP', color: stages.isEmpty ? Colors.black :  stages[currentPage - 1] == 1 ? Colors.white : Colors.black),
                                      ),
                                    ).applyConstraint(
                                      left: rId(1).right,
                                      widthPercent: 0.25,
                                      width: matchConstraint,
                                      widthPercentageAnchor: PercentageAnchor.parent,
                                      top: parent.top,
                                      bottom: parent.bottom,
                                    ),
                                    GestureDetector(
                                        onTap: () {
                                          setState(() {
                                            stages[currentPage - 1] = 3;
                                          });
                                        },
                                        child: Container(
                                          alignment: Alignment.center,
                                          decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(15)),
                                            color: stages.isEmpty ? Colors.transparent : stages[currentPage - 1] == 3 ? themeColor : Colors.transparent,
                                          ),
                                          child: F11TitleText('REM', color: stages.isEmpty ? Colors.black : stages[currentPage - 1] == 3 ? Colors.white : Colors.black),
                                        )
                                    ).applyConstraint(
                                      left: rId(2).right,
                                      widthPercent: 0.25,
                                      width: matchConstraint,
                                      widthPercentageAnchor: PercentageAnchor.parent,
                                      top: parent.top,
                                      bottom: parent.bottom,
                                    ),
                                    // GestureDetector(
                                    //     onTap: () {
                                    //       setState(() {
                                    //         stages[currentPage - 1] = 5;
                                    //       });
                                    //     },
                                    //     child: Container(
                                    //       alignment: Alignment.center,
                                    //       decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(15)),
                                    //         color: stages.isEmpty ? Colors.transparent : stages[currentPage - 1] == 5 ? themeColor : Colors.transparent,
                                    //       ),
                                    //       child: F11TitleText(
                                    //           'UN', color: stages.isEmpty ? Colors.black : stages[currentPage - 1] == 5 ? Colors.white : Colors.black),
                                    //     )
                                    // ).applyConstraint(
                                    //   left: rId(3).right,
                                    //   widthPercent: 0.2,
                                    //   width: matchConstraint,
                                    //   widthPercentageAnchor: PercentageAnchor.parent,
                                    //   top: parent.top,
                                    //   bottom: parent.bottom,
                                    // ),
                                    Visibility(
                                        visible: stages.isNotEmpty && stages[currentPage-1] != 4 && stages[currentPage - 1] != 5 && stages[currentPage-1] != 2,
                                        child: LineWidget(width: 0.5, height: 10)
                                    ).applyConstraint(
                                        left:rId(1).left,
                                        width: 0.5,
                                        top: rId(0).top,
                                        bottom: stages.isNotEmpty && stages[currentPage-1] != 4 && stages[currentPage - 1] != 5 && stages[currentPage-1] != 2 ? rId(1).bottom : rId(0).top,
                                        height: matchConstraint
                                    ),
                                    Visibility(
                                        visible: stages.isNotEmpty && stages[currentPage-1] != 2 && stages[currentPage-1] != 1,
                                        child: LineWidget(width: 0.5, height: 10)
                                    ).applyConstraint(
                                        left:rId(2).left,
                                        width: 0.5,
                                        top: rId(0).top,
                                        bottom: rId(2).bottom,
                                        height: matchConstraint
                                    ),
                                    Visibility(
                                        visible: stages.isNotEmpty && stages[currentPage-1] != 1 && stages[currentPage-1] != 3,
                                        child: LineWidget(width: 0.5, height: 10)
                                    ).applyConstraint(
                                        left:rId(3).left,
                                        width: 0.5,
                                        top: rId(0).top,
                                        bottom: rId(3).bottom,
                                        height: matchConstraint
                                    ),
                                    Visibility(
                                        visible: stages.isNotEmpty && stages[currentPage-1] != 3,
                                        child: LineWidget(width: 0.5, height: 10)
                                    ).applyConstraint(
                                        left:rId(4).left,
                                        width: 0.5,
                                        top: rId(0).top,
                                        bottom: rId(4).bottom,
                                        height: matchConstraint
                                    ),
                                    // Visibility(
                                    //     visible: stages.isNotEmpty && stages[currentPage-1] != 5,
                                    //     child: LineWidget(width: 0.5, height: 10)
                                    // ).applyConstraint(
                                    //     left:rId(5).left,
                                    //     width: 0.5,
                                    //     top: rId(0).top,
                                    //     bottom: rId(5).bottom,
                                    //     height: matchConstraint
                                    // ),
                                  ],
                                )),
                          ),
                          const HorPadding(10),
                        ],
                      )
                    ],
                  ),
                ).applyConstraint(
                    topLeftTo: parent,
                    bottom: parent.bottom,
                    height: matchConstraint,
                    widthPercentageAnchor: PercentageAnchor.parent,
                    width: matchConstraint,
                    widthPercent: 0.45),
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w)), color: Colors.white,
                  ),
                  child: ConstraintLayout(
                    children: [
                      const F11TitleText('功能操作', color: F1TextColor).applyConstraint(
                        left: parent.left.margin(15),
                        top: parent.top.margin(8),
                      ),
                      CommonBtn(
                        title: '重置所有分期',
                        callback: () {
                          entry = OverlayEntry(builder: (ctx) {
                            return VerticalCommonAlert(
                                title: '重置所有分期',
                                msg: '是否确认重置所有分期？重置后无法恢复',
                                callback: (index) {
                                  setState(() {
                                    // stages = oldStages;
                                    PreferencesHelper.setStages(edfName, []);
                                    stages.clear();
                                    oldStages.clear();
                                    for(int i = 0; i < entity.data!.data!.sleepStage!.length; i ++) {
                                      String stage = entity.data!.data!.sleepStage![i];
                                      stages.add(int.parse(stage));
                                    }
                                    for (int i = 0; i < stages.length; i++) {
                                      oldStages.add(stages[i]);
                                    }
                                    for (int i = 0; i < oldStages.length; i ++) {
                                      stages.add(oldStages[i]);
                                    }
                                    currentPage = 1;
                                  });
                                },
                                entry: entry!);
                          });
                          Overlay.of(context).insert(entry!);
                        },
                        fontSize: 11,
                      ).applyConstraint(
                          top: rId(0).bottom.margin(4),
                          height: 28,
                          left: rId(0).left,
                          widthPercent: 0.35,
                          widthPercentageAnchor: PercentageAnchor.parent,
                          width: matchConstraint),
                      CommonBtn(
                        title: '暂存',
                        callback: () {
                          _saveStages();
                        },
                        fontSize: 11,
                      ).applyConstraint(
                          top: rId(1).top,
                          left: rId(1).right.margin(10),
                          widthPercent: 0.20,
                          widthPercentageAnchor: PercentageAnchor.parent,
                          width: matchConstraint,
                          height: 28),
                      GestureDetector(
                          onTap: () {
                            _endLogic();
                          },
                          child: Container(
                            alignment: Alignment.center,
                            decoration: BoxDecoration(borderRadius: const BorderRadius.all(Radius.circular(15)),
                                border: Border.all(color: const Color(0xFFFF76A7))),
                            child: const F11TitleText('结束', color: Color(0xFFFF76A7)),
                          )
                      ).applyConstraint(
                          left: rId(2).right.margin(10),
                          top: rId(2).top,
                          height: 28,
                          widthPercent: 0.20,
                          widthPercentageAnchor: PercentageAnchor.parent,
                          width: matchConstraint
                      ),
                    ],
                  ),
                ).applyConstraint(
                    topRightTo: parent,
                    bottom: parent.bottom,
                    height: matchConstraint,
                    widthPercentageAnchor: PercentageAnchor.parent,
                    width: matchConstraint,
                    widthPercent: 0.35),
                Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(7.5.w)), color: Colors.white,
                  ),
                  child: ConstraintLayout(
                    children: [
                      const F11TitleText('事件标定', color: F1TextColor).applyConstraint(
                        left: parent.left.margin(15),
                        top: parent.top.margin(8),
                      ),
                      GestureDetector(
                          onTap: () {
                            entry = OverlayEntry(
                                builder: (ctx) {
                                  return AwakeningAlertView(
                                    topX: awakenImageOffset!.dx - 8,
                                    topY: awakenImageOffset!.dy + 15,
                                    entry: entry!,
                                  );
                                });
                            Overlay.of(context).insert(entry!);
                          },
                          child: Image.asset(
                            stageQuestionIcon,
                            width: 16,
                            height: 16,
                            key: awakenImageKey,
                          )).applyConstraint(
                          right: parent.right.margin(16),
                          centerVerticalTo: rId(0),
                          clickPadding: EdgeInsets.all(20),
                          size: 16),
                      Container(
                        child: Container(
                          alignment: Alignment.center,
                          decoration: const BoxDecoration(color: Color(0xFFF78554), borderRadius: BorderRadius.all(Radius.circular(2.5)),
                          ),
                          key: awakenTextKey,
                          child: const F11TitleText(
                            '微觉醒',
                            color: Colors.white,
                          ),
                        ),
                      ).applyConstraint(
                          left: rId(0).left,
                          right: rId(1).left.margin(8),
                          width: matchConstraint,
                          top: rId(0).bottom.margin(5),
                          bottom: parent.bottom.margin(5),
                          height: matchConstraint)
                    ],
                  ),
                ).applyConstraint(
                  left: rId(0).right.margin(5),
                  right: rId(1).left.margin(5),
                  bottom: parent.bottom,
                  top: parent.top,
                  height: matchConstraint,
                  width: matchConstraint,
                )
              ],
            ),
          ).applyConstraint(
            right: parent.right.margin(5),
            height: matchConstraint,
            heightPercent: 0.16,
            left: parent.left.margin(5),
            width: matchConstraint,
            top: rId(1).bottom.margin(5),
            heightPercentageAnchor: PercentageAnchor.parent,
          ),
          Container(
            alignment: Alignment.center,
            decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(7.5.w)), color: Colors.white),
            child: Column(
              children: [
                const VerPadding(8),
                Row(
                  children: [
                    const HorPadding(15),
                    const F10TitleText('脑电(uv)30秒', color: F2TextColor),
                    Expanded(child: Container()),
                    Container(
                      height: 30,
                      width: 50.w,
                      decoration: const BoxDecoration(
                        color: Color(0xFFF3F5FA),
                        borderRadius: BorderRadius.all(Radius.circular(15)),
                      ),
                      child: ConstraintLayout(
                        children: [
                          F11TitleText('电压', color: Color(0xFF515151)).applyConstraint(
                            left: parent.left.margin(5.w),
                            centerVerticalTo: parent,
                          ),
                          GestureDetector(
                            onTap: () {
                              _enlarge();
                            },
                            child: Image.asset(
                              enlargeIcon,
                              width: 7.w,
                              height: 7.w,
                            ),
                          ).applyConstraint(
                              left: rId(0).right.margin(5.w),
                              width: 7.w,
                              height: 7.w,
                              centerVerticalTo: parent,
                              clickPadding: EdgeInsets.fromLTRB(20, 20, 10, 20)
                          ),
                          GestureDetector(
                            onTap: () {
                              _enSmall();
                            },
                            child: Image.asset(
                              abbreviationIcon,
                              width: 7.w,
                              height: 7.w,
                            ),
                          ).applyConstraint(
                              left: rId(1).right.margin(6.w),
                              width: 7.w,
                              height: 7.w,
                              centerVerticalTo: parent,
                              clickPadding: EdgeInsets.fromLTRB(10, 20, 20, 20)
                          ),
                        ],
                      ),
                    ),
                    //   child: Row(
                    //     mainAxisAlignment: MainAxisAlignment.spaceAround,
                    //     children: [
                    //       const F11TitleText('电压', color: Color(0xFF515151)),
                    //       GestureDetector(
                    //         onTap: () {
                    //           _enlarge();
                    //         },
                    //         child: Image.asset(
                    //           enlargeIcon,
                    //           width: 17,
                    //           height: 17,
                    //         ),
                    //       ),
                    //       GestureDetector(
                    //         onTap: () {
                    //           _enSmall();
                    //         },
                    //         child: Image.asset(
                    //           abbreviationIcon,
                    //           width: 17,
                    //           height: 17,
                    //         ),
                    //       ),
                    //     ],
                    //   ),
                    // ),
                    const HorPadding(20),
                    GestureDetector(
                      onTap: () {
                        entry = OverlayEntry(builder: (ctx) {
                          return FilterAlertView(
                            topX: filterIconOffset!.dx,
                            topY: filterIconOffset!.dy,
                            entry: entry!,
                            callback: (id) {
                              if (id == 0) {
                                filterType = 2;
                              } else if (id == 1) {
                                filterType = 3;
                              } else if (id == 2) {
                                filterType = 1;
                              } else if (id == 3) {
                                filterType = 4;
                              }
                              readEdf();
                              setState(() {
                                filterType;
                              });
                            },
                          );
                        });
                        Overlay.of(context).insert(entry!);
                      },
                      child: Container(
                          key: filterIconKey,
                          width: 30,
                          height: 30,
                          decoration: const BoxDecoration(color: Color(0xFFF3F5FA), borderRadius: BorderRadius.all(Radius.circular(15))),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Image.asset(
                                dataFilterIcon,
                                width: 17,
                                height: 17,
                              ),
                            ],
                          )
                      ),
                    ),
                    const HorPadding(25),
                    GestureDetector(
                      onTap: () {
                        _refresh();
                      },
                      child: Container(
                          width: 30,
                          height: 30,
                          decoration: const BoxDecoration(color: Color(0xFFF3F5FA), borderRadius: BorderRadius.all(Radius.circular(15))),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Image.asset(
                                dataRefreshIcon,
                                width: _iconHeight(),
                                height: 17,
                              ),
                            ],
                          )),
                    ),
                    const HorPadding(20),
                  ],
                ),
                Expanded(
                    child: ConstraintLayout(
                      children: [
                        Column(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            F10TitleText('${(yAxis / 2).toInt()}', color: const Color(0xFFABABAB)),
                            F10TitleText('${(yAxis / 4).toInt()}', color: const Color(0xFFABABAB)),
                            const F10TitleText('0', color: Color(0xFFABABAB)),
                            F10TitleText('-${(yAxis / 4).toInt()}', color: const Color(0xFFABABAB)),
                            F10TitleText('-${(yAxis / 2).toInt()}', color: const Color(0xFFABABAB)),
                          ],
                        ).applyConstraint(
                            left: parent.left.margin(10),
                            top: parent.top,
                            bottom: parent.bottom,
                            height: matchConstraint,
                            width: 30),
                        Container(
                          child: StageSubPage(
                            key: eeWidgetKey,
                            datas: datas,
                            ratio: ratio,
                            yAsix: yAxis,
                          ),
                        ).applyConstraint(
                            left: rId(0).right,
                            right: parent.right,
                            top: rId(0).top,
                            bottom: parent.bottom,
                            width: matchConstraint)
                      ],
                    )),
                const Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    F11TitleText('0s', color: Color(0xFFABABAB)),
                    F11TitleText('3s', color: Color(0xFFABABAB)),
                    F11TitleText('6s', color: Color(0xFFABABAB)),
                    F11TitleText('9s', color: Color(0xFFABABAB)),
                    F11TitleText('12s', color: Color(0xFFABABAB)),
                    F11TitleText('15s', color: Color(0xFFABABAB)),
                    F11TitleText('18s', color: Color(0xFFABABAB)),
                    F11TitleText('21s', color: Color(0xFFABABAB)),
                    F11TitleText('24s', color: Color(0xFFABABAB)),
                    F11TitleText('27s', color: Color(0xFFABABAB)),
                    F11TitleText('30s', color: Color(0xFFABABAB)),
                  ],
                ),
                const VerPadding(5),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    _getPageBtn('上一页', 66, 30),
                    const HorPadding(17),
                    const F11TitleText('当前', color: Color(0xFF515151)),
                    const HorPadding(8),
                    _getPageBtn('$currentPage', 40, 30),
                    const HorPadding(8),
                    const F11TitleText('页', color: Color(0xFF515151)),
                    const HorPadding(17),
                    _getPageBtn('下一页', 66, 30),
                    const HorPadding(20),
                    F11TitleText('共$totalPage页', color: const Color(0xFF515151)),
                  ],
                ),
                const VerPadding(18),
              ],
            ),
          ).applyConstraint(
            right: parent.right.margin(5),
            height: matchConstraint,
            left: parent.left.margin(5),
            width: matchConstraint,
            top: rId(2).bottom.margin(3),
            bottom: parent.bottom.margin(3),
          ),
        ],
      ),
      Positioned(
          left: awakenTextX - statusBarHeight,
          top: Platform.isAndroid ? awakenTextY - statusBarHeight : awakenTextY,
          width: awakenTextWidth,
          height: awakenTextHeight,
          child: Visibility(
            visible: eventType == 0,
            child: Container(
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                color: Color(0xFFF78554),
                borderRadius: BorderRadius.all(Radius.circular(2.5)),
              ),
              child: const F11TitleText(
                '微觉醒',
                color: Colors.white,
              ),
            ),
          )),
    ];

    for (int i = 0; i < awakenModels.length; i ++) {
      AwakenModel model = awakenModels[i];
      if (model.page != currentPage) {
        continue;
      }
      widgets.add(
        Positioned(
          left: model.x - 1.w,
          top: model.y + 5.w,
          width: 1.5.w,
          height: eegWidgetSize == null ? 0 : eegWidgetSize!.height - 20,
          child: Visibility(
            visible: model.isShow,
            child: Container(
              alignment: Alignment.center,
              decoration: const BoxDecoration(
                color: Color(0xFFF78554),
                borderRadius: BorderRadius.all(Radius.circular(2.5)),
              ),
            ),
          )
        )
      );
    }

    return widgets;
  }

  double _iconHeight() {
    return 17 + 0.1 * filterType;
  }

  Widget _getPageBtn(String text, double width, double height) {
    return InkWell(
      onTap: () {
        if (text == '上一页') {
          currentPage--;
          if (currentPage < 1) {
            currentPage = 1;
            ToastUtils.showToast(msg: '已是第一页');
          } else {
            setState(() {
              currentPage;
              readEdf();
            });
          }
        } else if (text == '下一页') {
          currentPage++;
          if (currentPage > totalPage) {
            currentPage = totalPage;
            ToastUtils.showToast(msg: '已是最后一页');
          } else {
            setState(() {
              currentPage;
              readEdf();
            });
          }
        } else {
          entry = OverlayEntry(builder: (ctx) {
            return SimpleTextAlert(
              text: text,
              entry: entry!,
              callback: (page) {
                if (page > totalPage || page < 1) return;
                setState(() {
                  currentPage = page;
                  readEdf();
                });
              },
            );
          });
          Overlay.of(context).insert(entry!);
        }
      },
      child: Container(
        alignment: Alignment.center,
        height: height,
        width: width,
        decoration: const BoxDecoration(color: Color(0xFFF3F5FA), borderRadius: BorderRadius.all(Radius.circular(10))),
        child: F11TitleText(
          text,
          color: const Color(0xFF515151),
        ),
      ),
    );
  }

  ///电压放大计算
  void _enSmall() {
    setState(() {
      yAxis *= 0.2;
      ratio *= 0.2;
      yAxis = max(yAxis, minYAxis);
      ratio = max(ratio, 0.1);
    });
  }

  void _enlarge() {
    setState(() {
      yAxis /= 0.2;
      ratio /= 0.2;
      yAxis = min(yAxis, maxYAxis);
      ratio = min(ratio, 70);
    });
  }

  void _refresh() {
    setState(() {
      yAxis = 200;
      ratio = 1;
    });
  }

  void _endLogic() {
    // NetBusiness().resetStage(reportId, stages, [{'type':0, 'startTime':10, 'endTime':20}]).then((onValue){
    List<Map<String, dynamic>> eventList = [];
    for(int i = 0; i < awakenModels.length; i ++) {
      AwakenModel model = awakenModels[i];
      Map<String, dynamic> map = {};
      String abc = TimeUtils.timeStampToTimeStr(model.timeStamp);
      map['startTime'] = TimeUtils.timeStampToTimeStr(model.timeStamp);
      map['endTime'] = map['startTime'];
      map['page'] = model.page.toString();
      map['eventType'] = 0.toString();
      eventList.add(map);
    }
    LogUtils.log('eventList=${eventList.toString()}');
    NetBusiness().resetStage(reportId, stages, eventList).then((onValue) async {
      if (onValue) {
        ToastUtils.showToast(msg: '分期成功');
        PreferencesHelper.setStages(edfName, []);
        ///删除缓存 pdf 报告
        Directory directory = await getTemporaryDirectory();
        String path = '${directory.path}/${widget.id}.pdf';
        File(path).delete();
        ///返回上一页
        NavigatorUtil.pop(context);
      } else {
        ToastUtils.showToast(msg: '分期失败，请稍后再试');
      }
    });

  }

  void _saveStages() {
    List<String> saveStages = [];
    for (int i = 0; i < stages.length; i++) {
      saveStages.add('${stages[i]}');
    }
    PreferencesHelper.setStages(edfName, saveStages);
    ToastUtils.showToast(msg: '已暂存');
  }

  @override
  void initState() {
    // 强制横屏
    SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeLeft, DeviceOrientation.landscapeRight]);
    // 在控件渲染完成后执行的回调
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _findRenderObject();
    });
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);

    entity.data = ReportDetailData();
    NetBusiness().reportDetail(widget.id).then((onValue) async{
      entity = onValue;

      reportId = entity.data!.id!;
      startTimeStamp = TimeUtils.getCurrentMillTimeStamp(entity.data!.startTime);
      int edfNameId = entity.data!.fileUrl!.lastIndexOf('/');
      edfName = entity.data!.fileUrl!.substring(edfNameId+1);
      localEdfPath = await getEdfFile(entity.data!.fileUrl!, edfName);
      if (localEdfPath.isNotEmpty) {
        List<String>? savedStages = PreferencesHelper.getStages(edfName);
        if (savedStages != null && savedStages.isNotEmpty) {
          stages.clear();
          for (int i = 0; i < savedStages.length; i++) {
            int stage = int.parse(savedStages[i]);
            stages.add(stage);
            oldStages.add(stage);
          }
        } else {
          stages.clear();
          if (entity.data!.data != null) {
            for(int i = 0; i < entity.data!.data!.sleepStage!.length; i ++) {
              String stage = entity.data!.data!.sleepStage![i];
              stages.add(int.parse(stage));
            }
            for (int i = 0; i < stages.length; i++) {
              oldStages.add(stages[i]);
            }
          }
        }
      }
      setState(() {
        stages;
        List<Map<String, dynamic>> list = [];
        if (entity.data!.data != null) {
          if (entity.data!.data!.eventList is List) {
            for (var item in entity.data!.data!.eventList) {
              if (item is Map) {
                list.add(Map<String, dynamic>.from(item));
              }
            }
          }
        }
        Timer(Duration(seconds: 2), (){
          for (int i = 0; i < list!.length; i ++) {
            Map event = list![i];
            if (event['eventType'] != '0') {
              continue;
            }
            int curTimeStamp = TimeUtils.getCurrentMillTimeStamp(event['startTime']);
            double posX = (curTimeStamp-startTimeStamp) % 30000 / 30000 * eegWidgetSize!.width + 40;
            AwakenModel model = AwakenModel(posX, eegWidgetOffset!.dy, true, false, posX, eegWidgetOffset!.dy);
            model.page = int.parse(event['page']);
            model.timeStamp = TimeUtils.getCurrentMillTimeStamp(event['startTime']);
            awakenModels.add(model);
          }

          readEdf();
        });
      });
    });
  }

  ///读取或下载文件
  Future<String> getEdfFile(String fileUrl, String fileName) async{
    ///是否需要下载文件
    Directory directory = await getTemporaryDirectory();
    String path = '${directory.path}/$fileName';
    if (!File(path).existsSync()) {
      Loading.getIns().loading(msg: '正在下载edf文件');
      bool downloadResult = await NetBusiness().downloadingFile(url: fileUrl, saveFileNamed: path);
      Loading.getIns().hide();
      return downloadResult ? path : '';
    } else {
      return path;
    }
  }

  void readEdf() async {
    var native = WchPlugin();
    String filePath = localEdfPath;
    List<int> list = native.readEdfData(filePath, currentPage - 1).cast();
    datas.clear();
    for (int i = 0; i < list.length; i++) {
      int val = native.filterDataFunc(list[i], filterType);
      datas.add(val);
    }
    native.releaseFilter();
    setState(() {
      currentPage;
      datas;
    });

    if (totalPage == 0) {
      int page = native.getTotalPage(filePath);
      // LogUtils.log('page=$page');
      if (stages.length < page) {
        ///补数据
        for (int i = stages.length; i < page; i ++) {
          stages.add(4);
          oldStages.add(4);
        }
      }
      setState(() {
        totalPage = page;
      });
    }

    if (stages.isEmpty) {
      for(int i = 0; i < totalPage; i ++) {
        stages.add(4);
        oldStages.add(4);
      }
    }
  }

  // 如果控件用了Transform平移旋转等, 获取到的坐标也会变化
  _findRenderObject() {
    Timer(Duration(seconds: 2), (){
      RenderObject? _renderObj = awakenImageKey.currentContext?.findRenderObject();
      if (_renderObj != null) {
        RenderBox _renderBox = _renderObj as RenderBox;
        awakenImageOffset = _renderBox.localToGlobal(Offset.zero);
      }

      RenderObject? _renderObj2 = awakenTextKey.currentContext?.findRenderObject();
      if (_renderObj2 != null) {
        RenderBox _renderBox = _renderObj2 as RenderBox;
        Offset offset = _renderBox.localToGlobal(Offset.zero);
        setState(() {
          awakenTextY = offset.dy - 10;
          awakenTextX = offset.dx;
          awakenTextWidth = _renderBox.size.width;
          awakenTextHeight = _renderBox.size.height;
        });
        originAwakenTextX = awakenTextX;
        originAwakenTextY = awakenTextY;
        LogUtils.log('originAwakenTextX=$originAwakenTextX');
        LogUtils.log('originAwakenTextY=$originAwakenTextY');
        LogUtils.log('awakenTextWidth=$awakenTextWidth');
        LogUtils.log('awakenTextHeight=$awakenTextHeight');
      }

      RenderObject? _renderObj3 = filterIconKey.currentContext?.findRenderObject();
      if (_renderObj3 != null) {
        RenderBox _renderBox = _renderObj3 as RenderBox;
        filterIconOffset = _renderBox.localToGlobal(Offset.zero);
      }

      RenderObject? _renderObj4 = eeWidgetKey.currentContext?.findRenderObject();
      if (_renderObj4 != null) {
        LogUtils.log('_renderObj4');
        RenderBox _renderBox = _renderObj4 as RenderBox;
        eegWidgetSize = _renderBox.size;
        eegWidgetOffset = _renderBox.localToGlobal(Offset.zero);
      }

      RenderObject? _renderObj5 = titleWidgetKey.currentContext?.findRenderObject();
      if (_renderObj5 != null) {
        RenderBox _renderBox = _renderObj5 as RenderBox;
        titleWidgetHeight = _renderBox.localToGlobal(Offset.zero).dy;
        LogUtils.log('titleWidgetHeight=$titleWidgetHeight');
      }
    });
  }

  @override
  void dispose() {
    super.dispose();
    SystemChrome.setPreferredOrientations(
        [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.edgeToEdge, overlays: []);
  }
}

class AwakenModel {
  double x;
  double y;
  double originX;
  double originY;
  bool isShow;
  bool isPressed;//是否被按下
  int timeStamp = 0;
  String time = '';
  int page = 0;

  AwakenModel(this.x, this.y, this.isShow, this.isPressed, this.originX, this.originY);

}
